package seven_topics_Exchange;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import util.RabbitMqUtils;

/**
 * @BelongsProject: RabbitMQ
 * @BelongsPackage: seven_topics_Exchange
 * @Author: HUI
 * @CreateTime: 2022-04-13 23:28
 * @Description: 接收消息
 */
public class MyWorks2 {
    private static final String EXCHANGE_NAME = "topics_logs";

    public void getWork() throws Exception {
        //Q1等于main，Q2等于子线程
        String threadName = Thread.currentThread().getName();
        Channel channel = RabbitMqUtils.getChannel();

        //指定交换机模式
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String receivedMessage = new String(delivery.getBody());
            System.out.println(threadName + "接收到消息:" + receivedMessage);
        };

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println(consumerTag + "消费者取消消费接口回调逻辑");
        };


        String Q1 = "Q1";
        String Q2 = "Q2";
        //将临时队列与交换机进行绑定，routingKey是队列与交换机的之间的绑定key
        if ("main".equalsIgnoreCase(threadName)) {
            channel.queueDeclare(Q1, false, false, false, null);
            channel.queueBind(Q1, EXCHANGE_NAME,  "*.orange.*");
            channel.basicConsume(Q1, true, deliverCallback, cancelCallback);
        } else {
            channel.queueDeclare(Q2, false, false, false, null);
            channel.queueBind(Q2, EXCHANGE_NAME, "*.*.rabbit");
            channel.queueBind(Q2, EXCHANGE_NAME, "lazy.#");
            channel.basicConsume(Q2, true, deliverCallback, cancelCallback);
        }

        System.out.println(threadName + "消费者启动等待消费.................. ");

    }


    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            try {
                new MyWorks2().getWork();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


        new MyWorks2().getWork();

    }
}
